package com.zk.algorithm.string;

import com.zk.algorithm.Utils;
import com.zk.algorithm.annotation.Easy;
import com.zk.algorithm.annotation.LeetCodeExplore;

@Easy
@LeetCodeExplore
public class ValidPalindrome {

    public static void main(String...args) {
        ValidPalindrome validPalindrome = new ValidPalindrome();

        boolean is = false;
//        is = validPalindrome.isPalindrome("A man, a plan, a canal: Panama");
        is = validPalindrome.isPalindrome("0P");

        Utils.println(is);
    }

    public boolean isPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return true;
        }

        int begin = 0;
        int end = s.length() - 1;
        char[] array = s.toCharArray();

        while (begin <= end) {
            char left = array[begin];
            char right = array[end];

            if (!isAlpha(left)) {
                begin++;
            } else if (!isAlpha(right)) {
                end--;
            } else if (toLowerCase(left) == toLowerCase(right)) {
                begin++;
                end--;
            } else {
                return false;
            }
        }

        return true;
    }

    private boolean isAlpha(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
    }

    private char toLowerCase(char c) {
        if (c >= 'A' && c <= 'Z') {
            return (char)(c + 32);
        }

        return c;
    }

}
